import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/intl.dart';

import '../../common/index.dart';
import 'widgets/message_bubble.dart';
import 'widgets/image_viewer.dart';
import 'utils/image_cache_utils.dart';

class ChatPage extends ConsumerStatefulWidget {
  const ChatPage({super.key, required this.userId});
  final String userId;

  @override
  ConsumerState<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends ConsumerState<ChatPage> {
  UserEntity? _partnerUser;
  List<MessageEntity> _messages = [];
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final FocusNode _messageFocusNode = FocusNode();
  bool _isSending = false;

  // 图片缓存工具实例
  final ImageCacheUtils _imageCacheUtils = ImageCacheUtils();

  @override
  void initState() {
    super.initState();
    _loadUserData();
    _loadMessages();
    _markMessagesAsRead();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _loadUserData();
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    _messageFocusNode.dispose();
    super.dispose();
  }

  Future<void> _loadUserData() async {
    final partnerUser = await UserService.getUserById(widget.userId);
    if (partnerUser != null) {
      setState(() {
        _partnerUser = partnerUser;
      });
    }
  }

  void _loadMessages() {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser != null) {
      final messages = MessageService.getConversation(
        currentUser.id,
        widget.userId,
      );
      setState(() {
        _messages = messages;
      });

      // 预加载所有图片尺寸
      _preloadImageSizes();

      // 加载完消息后滚动到底部
      _scrollToBottom();
    }
  }

  // 预加载所有图片尺寸
  void _preloadImageSizes() {
    final imageUrls = _messages
        .where((message) => message.type == MessageType.image)
        .map((message) => message.content)
        .toList();

    if (imageUrls.isNotEmpty) {
      _imageCacheUtils
          .preloadImageSizes(imageUrls)
          .then((_) {
            if (mounted) {
              setState(() {
                // 触发重建以显示已加载的图片
              });
            }
          })
          .catchError((error) {
            // 忽略错误，使用默认尺寸
          });
    }
  }

  // 标记消息为已读
  Future<void> _markMessagesAsRead() async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser != null) {
      // 使用 messageProvider 来标记对话为已读，这样会自动更新相关状态
      await ref
          .read(messageProvider.notifier)
          .markConversationAsRead(currentUser.id, widget.userId);
    }
  }

  // 发送文字消息
  Future<void> _sendTextMessage() async {
    final text = _messageController.text.trim();
    if (text.isEmpty || _isSending) return;

    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) return;

    setState(() {
      _isSending = true;
    });

    try {
      final messageNotifier = ref.read(messageProvider.notifier);
      final success = await messageNotifier.sendMessage(
        senderId: currentUser.id,
        receiverId: widget.userId,
        content: text,
        type: MessageType.text,
      );

      if (success) {
        _messageController.clear();
        _loadMessages();
        _scrollToBottom();
        // 重新聚焦输入框
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            _messageFocusNode.requestFocus();
          }
        });
      }
    } catch (e) {
      debugPrint('发送消息失败: $e');
      _showErrorMessage('Failed to send message');
    } finally {
      setState(() {
        _isSending = false;
      });
    }
  }

  // 选择并发送图片
  Future<void> _pickAndSendImage() async {
    if (_isSending) return;

    try {
      final imagePath = await ImagePickerUtil.pickImageFromGalleryForChat();
      if (imagePath != null) {
        await _sendImageMessage(imagePath);
      }
    } catch (e) {
      debugPrint('选择图片失败: $e');
      _showErrorMessage('Failed to select image');
    }
  }

  // 发送图片消息
  Future<void> _sendImageMessage(String imagePath) async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) return;

    setState(() {
      _isSending = true;
    });

    try {
      final messageNotifier = ref.read(messageProvider.notifier);
      final success = await messageNotifier.sendMessage(
        senderId: currentUser.id,
        receiverId: widget.userId,
        content: imagePath,
        type: MessageType.image,
      );

      if (success) {
        _loadMessages();
        _scrollToBottom();
      }
    } catch (e) {
      debugPrint('发送图片失败: $e');
      _showErrorMessage('Failed to send image');
    } finally {
      setState(() {
        _isSending = false;
      });
    }
  }

  // 滚动到底部
  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  // 显示错误提示
  void _showErrorMessage(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Colors.red,
          duration: const Duration(seconds: 2),
        ),
      );
    }
  }

  // 处理图片点击事件
  void _onImageTap(String imageUrl, String heroTag) {
    showImageViewer(context, imageUrl, heroTag: heroTag);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: Text(
          _partnerUser?.username ?? 'Loading...',
          style: TextStyle(
            color: Colors.white,
            fontSize: 20.sp,
            fontFamily: 'Roboto',
            fontWeight: FontWeight.w400,
          ),
        ),
        backgroundColor: Color(0xFFFF8C00),
        leading: IconButton(
          onPressed: () {
            context.goBack();
          },
          icon: Icon(Icons.arrow_back_ios_new_rounded, color: Colors.white),
        ),
        actions: [
          IconButton(
            icon: SvgPicture.asset(MyIcons.report, width: 28.w, height: 28.h),
            onPressed: _showReportDialog,
          ),
        ],
      ),
      resizeToAvoidBottomInset: true,
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          color: Colors.black,
          child: Column(
            children: [
              SizedBox(height: 75.h),
              Expanded(
                child: RefreshIndicator(
                  onRefresh: () async {
                    _loadMessages();
                  },
                  child: SingleChildScrollView(
                    controller: _scrollController,
                    padding: EdgeInsets.symmetric(horizontal: 5.w),
                    child: Column(
                      children: [
                        SizedBox(height: 20.h),
                        ..._buildMessageList(),
                        SizedBox(height: 20.h), // 减少底部间距
                      ],
                    ),
                  ),
                ),
              ),

              // 分割线
              Container(
                height: 1.h,
                width: MediaQuery.of(context).size.width,
                decoration: BoxDecoration(
                  border: Border.all(
                    color: const Color(0xFFFFD29B),
                    width: 1.w,
                  ),
                ),
              ),

              // 发送区域 - 固定高度，会跟随键盘弹起
              Container(
                width: MediaQuery.of(context).size.width,
                color: Colors.black,
                padding: EdgeInsets.only(
                  left: 20.w,
                  right: 20.w,
                  top: 10.h,
                  bottom: MediaQuery.of(context).padding.bottom + 10.h,
                ),
                child: _buildSend(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 发送区域
  Widget _buildSend() {
    return SizedBox(
      height: 50.h, // 固定发送区域高度
      child: Row(
        spacing: 11.w,
        children: [
          Container(
            width: 245.w,
            height: 35.h,
            decoration: ShapeDecoration(
              color: const Color(0xFFFF8C00),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(200.r),
              ),
            ),
            padding: EdgeInsets.symmetric(horizontal: 10.w),
            child: TextField(
              controller: _messageController,
              focusNode: _messageFocusNode,
              textInputAction: TextInputAction.send,
              maxLines: null,
              expands: true,
              enabled: !_isSending,
              onSubmitted: (_) => _sendTextMessage(),
              style: TextStyle(
                color: Colors.white,
                fontSize: 12.sp,
                fontFamily: 'Roboto',
                fontWeight: FontWeight.w400,
              ),
              cursorColor: Colors.white,
              decoration: InputDecoration(
                border: InputBorder.none,
                hintText: _isSending ? 'Sending...' : 'Say something...',
                hintStyle: TextStyle(
                  color: Colors.white.withValues(alpha: 0.75),
                  fontSize: 12.sp,
                  fontFamily: 'Roboto',
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap: _isSending ? null : _pickAndSendImage,
            child: Opacity(
              opacity: _isSending ? 0.5 : 1.0,
              child: SvgPicture.asset(MyIcons.pic, width: 22.w, height: 20.h),
            ),
          ),
          GestureDetector(
            onTap: _isSending ? null : _sendTextMessage,
            child: Container(
              width: 43.w,
              height: 36.h,
              decoration: ShapeDecoration(
                color: _isSending
                    ? const Color(0xFFFF8C00).withValues(alpha: 0.5)
                    : const Color(0xFFFF8C00),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.r),
                ),
              ),
              child: Center(
                child: _isSending
                    ? SizedBox(
                        width: 12.w,
                        height: 12.h,
                        child: CircularProgressIndicator(
                          strokeWidth: 2.w,
                          valueColor: const AlwaysStoppedAnimation<Color>(
                            Colors.white,
                          ),
                        ),
                      )
                    : Text(
                        'Send',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12.sp,
                          fontFamily: 'Roboto',
                          fontWeight: FontWeight.w400,
                        ),
                      ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建消息列表
  List<Widget> _buildMessageList() {
    final currentUser = ref.watch(currentUserProvider);
    if (currentUser == null || _messages.isEmpty) {
      return [];
    }

    List<Widget> widgets = [];

    for (int i = 0; i < _messages.length; i++) {
      final message = _messages[i];
      final isCurrentUser = message.senderId == currentUser.id;

      // 检查是否需要显示时间
      bool showTime = false;
      if (i == 0) {
        showTime = true; // 第一条消息总是显示时间
      } else {
        final previousMessage = _messages[i - 1];
        final timeDifference = message.timestamp.difference(
          previousMessage.timestamp,
        );
        showTime = timeDifference.inMinutes >= 5; // 超过5分钟显示时间
      }

      // 添加时间显示
      if (showTime) {
        widgets.add(_buildTimeDisplay(message.timestamp));
      }

      // 添加消息气泡
      widgets.add(_buildMessageBubble(message, isCurrentUser));

      // 添加间距
      widgets.add(SizedBox(height: 10.h));
    }

    return widgets;
  }

  // 构建时间显示
  Widget _buildTimeDisplay(DateTime timestamp) {
    final timeFormat = DateFormat('HH:mm');
    final timeString = timeFormat.format(timestamp);

    return Container(
      margin: EdgeInsets.symmetric(vertical: 10.h),
      child: Center(
        child: Text(
          timeString,
          style: TextStyle(
            color: Colors.white.withValues(alpha: 0.6),
            fontSize: 12.sp,
            fontFamily: 'Roboto',
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
    );
  }

  // 构建消息气泡
  Widget _buildMessageBubble(MessageEntity message, bool isCurrentUser) {
    final currentUser = ref.watch(currentUserProvider);

    return Align(
      alignment: isCurrentUser ? Alignment.centerRight : Alignment.centerLeft,
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 10.w),
        child: MessageBubble(
          message: message,
          isCurrentUser: isCurrentUser,
          currentUser: currentUser,
          partnerUser: _partnerUser,
          imageCacheUtils: _imageCacheUtils,
          onImageTap: _onImageTap,
        ),
      ),
    );
  }

  /// 显示举报对话框
  void _showReportDialog() {
    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return ReportDialog(
          targetId: widget.userId,
          reportType: ReportType.chat,
          title: 'Report Chat',
          onReportSuccess: () {
            // 举报成功后，返回消息列表页面并刷新对话列表
            context.goBack();
            // 刷新消息列表数据
            final currentUser = UserService.getCurrentUser();
            if (currentUser != null) {
              ref
                  .read(messageProvider.notifier)
                  .loadConversations(currentUser.id);
            }
          },
        );
      },
    );
  }
}
